#coding: utf-8
import feedparser
import re
import httplib
import socket

class KTXP(object):
    def __init__(self):
        super(KTXP,self).__init__()
        
#        from utils.thread_pool import ThreadPool
#        ThreadPool().addTask(self._job)
        self._job() 

    def _get_http(self,url):
        link=url.replace("http://","")
        temp=link.split("/")
        host=temp[0]
        url="/" + "/".join(temp[1:])
        
        try:
            rss_conn=httplib.HTTPConnection(host,80,False,5)
            rss_conn.request("GET", url)  
        except socket.timeout:
            print "Timeout"
        except:
            import traceback
            traceback.print_exc()
        else:
            response=rss_conn.getresponse()
            return response.read() 
    
    def _job(self):
        url="http://bt.ktxp.com/rss.xml"
        rss=self._get_http(url)
        if not rss:
            return
        feed=feedparser.parse(rss)
                
        self._items=[]
        for item in feed["items"]:
            self._items.append({"title":item['title'],
                                "link":item['link']})
            
        print self._get_torrent(self._items[0]["link"])
            
    def getTitles(self):
        return [(i,self._items[i]["title"]) for i in range(len(self._items))]
    
    def getFile(self,item_index):
        return self._get_torrent(self._items[item_index]["link"])
    
    def _get_torrent(self,link):
        html=self._get_http(link)
        p=re.compile(r'href=.+\>默认下载点', re.I)
        
        result=p.findall(html)
        print result[0]
